import { message } from 'antd';
import { getPackagePage, addPackage, deletePackage, getPackageInfo, checkPackage, releasePackage, updatePackage } from '../services/api';

export default {
  namespace: 'packages',

  state: {
    packageList: [],
    packageInfo: {},
  },

  effects: {
    *getPackagePage({ payload }, { call, put }) {
      const response = yield call(getPackagePage, payload);
      yield put({
        type: 'savePackageList',
        payload: response,
      });
    },
    *addPackage({ payload, callback }, { call }) {
      const response = yield call(addPackage, payload);
      if (response.code === 0) {
        if (callback) callback();
      }
    },
    *deletePackage({ payload, callback }, { call }) {
      const response = yield call(deletePackage, payload);
      if (response.code === 0) {
        message.success('删除成功');
      } else {
        message.error('删除失败');
      }
      if (callback) callback();
    },
    *getPackageInfo({ payload, callback }, { call, put }) {
      const response = yield call(getPackageInfo, payload);
      yield put({
        type: 'savePackageInfo',
        payload: response,
      });
      if (callback) callback();
    },
    *updatePackage({ payload, callback }, { call, put }) {
      const response = yield call(updatePackage, payload);
      if (response.code === 0) {
        message.success('修改成功');
      } else {
        message.error('修改失败');
      }
      if (callback) callback();
    },
    *checkPackage({ payload, callback }, { call, put }) {
      const response = yield call(checkPackage, payload);
      if (response.code === 0) {
        message.success('审核成功');
        if (callback) callback();
      } else {
        message.error('审核失败');
      }
    },
    *releasePackage({ payload, callback }, { call, put }) {
      const response = yield call(releasePackage, payload);
      if (response.code === 0) {
        message.success('发布成功');
        if (callback) callback();
      } else {
        message.error('发布失败');
      }
    },
  },

  reducers: {
    savePackageInfo(state, action) {
      return {
        ...state,
        packageInfo: action.payload.data,
      };
    },
    savePackageList(state, action) {
      return {
        ...state,
        packageList: action.payload.data,
      };
    },
  },
};
